<template>
  <div class="questionnaire">
    <div style="position: relative;width: 100%">
      <img src="../assets/bg.png" style="width: 100%;" />
      <div style="width: 100%;display: flex;justify-content: center;" class="contentBg">
        <div style="width: 100%">
          <van-form @submit="onSubmit" @failed="onFailed" ref="vanFormRef">
            <van-cell-group inset style="background: transparent;">
              <div style="color: #2E6CE8" class="contentBg-title">
                一、部门评测 <span>（最少有一个D和一个E）</span></div>
              <div v-for="target in DepartmentList" :key="target.id">
                <van-field class="zdyField" required name="financeData" :label="target.label"
                  :rules="[{ required: true, message: `请完成${target.label}测评等级` }]">
                  <template #input>
                    <div>
                      <van-radio-group v-model="formState[target.key]">
                        <van-radio name="A">A</van-radio>
                        <van-radio name="B">B</van-radio>
                        <van-radio name="C">C</van-radio>
                        <van-radio name="D">D</van-radio>
                        <van-radio name="E">E</van-radio>
                      </van-radio-group>
                    </div>
                  </template>
                </van-field>
                <van-field class="zdyField" required v-if="formState[target.key] == 'D' || formState[target.key] == 'E'"
                  v-model="formState[`ReasonD${target.id}`]" label="原因说明：" type="textarea" placeholder="请输入原因" rows="3"
                  :rules="[{ required: true, message: `请输入原因` }]" autosize />

              </div>

              <div style="color: #2E6CE8;margin-top: 30px;" class="contentBg-title">
                二、员工评测 <span>(A固定评三个,D和E最少三个)</span></div>
              <div v-for="target in EmployeesList" :key="target.key">
                <van-field class="zdyField" required name="financeData" :label="target.label"
                  :rules="[{ required: true, message: `请完成${target.label}员工测评等级` }]">
                  <template #input>
                    <div>
                      <van-radio-group v-model="formState[target.key]">
                        <van-radio name="A">A</van-radio>
                        <van-radio name="B">B</van-radio>
                        <van-radio name="C">C</van-radio>
                        <van-radio name="D">D</van-radio>
                        <van-radio name="E">E</van-radio>
                      </van-radio-group>
                    </div>
                  </template>
                </van-field>
                <van-field class="zdyField" required v-if="formState[target.key] == 'D' || formState[target.key] == 'E'"
                  v-model="formState[`ReasonE${target.id}`]" label="原因说明：" type="textarea" placeholder="请输入原因"
                  rows="3" :rules="[{ required: true, message: `请输入原因` }]" autosize />
              </div>
              <div style="margin: .4267rem;width: 80%;">
                <van-button round block type="primary" native-type="submit">
                  提交
                </van-button>

              </div>
            </van-cell-group>
          </van-form>
        </div>
      </div>
    </div>
    <van-dialog v-model:show="errorShow" title="选择错误" :show-cancel-button="false">
      <div style="display: flex;flex-direction: column;gap: 10px;justify-content: center; align-items: center;padding: 20px;"> 
        <img src="../assets/error.png" class="errorImg" />
        <p style="margin: 0;">{{ errorMsg }}</p>
      </div>
     
    </van-dialog>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { EmployeesQueryByCond, DepartmentQueryByCond,RecordAdd } from "../api/user"
import { ref, toRaw, onMounted, watch } from "vue";
import { debounce } from "../utils/index"
const showPopup = ref(false)
const router = useRouter();
const EmployeesList = ref([])
const DepartmentList = ref([])
const errorShow=ref(false)
const errorMsg=ref("(A固定评三个,D和E最少三个)")
const formState = ref({
  
})

onMounted(() => {
  EmployeesQueryByCond({}, 100, 1).then(res => {
    if (res.data.code == 200) {
      EmployeesList.value = res.data.data.list.map((item, index) => {
        return {
          label: item.name,
          key: `Employees${item.id}`,
          id: item.id
        }
      })
    }

  })
  DepartmentQueryByCond({}, 100, 1).then(res => {
    if (res.data.code == 200) {
      DepartmentList.value = res.data.data.list.map((item, index) => {
        return {
          label: item.name,
          key: `Department${item.id}`,
          id: item.id
        }
      })
    }
  })
})


// 表单提交
const onSubmit = debounce(() => {
  handleAdd()
}, 1000)
const onFailed = (errorInfo) => {
  Toast.fail('提交失败,完善信息')
  console.log('failed', errorInfo);
}

const handleAdd = async () => {
  return new Promise(async (resolve, reject) => {
    
    let deptRecord = {};
    let userRecord = {};
    let userSituationRecord = {};
    let deptSituationRecord = {};
    Object.keys(formState.value).forEach(item => {
      if (item.includes('Employees')) {
        userRecord[item] = formState.value[item]
      } else if (item.includes('Department')) {
        deptRecord[item] = formState.value[item]
      } else if (item.includes('ReasonD')) {
        deptSituationRecord[item] = formState.value[item]
      } else if (item.includes('ReasonE')) {
        userSituationRecord[item] = formState.value[item]
      }

    })
    //判断部门至少一个D一个E
    if (!(Object.values(deptRecord).includes('D') && Object.values(deptRecord).includes('E')) ) {
      errorMsg.value="部门 (最少有一个D和一个E)"
      errorShow.value=true
      return
    }
     //判断员工(A固定评三个,D和E最少三个)
    if(!checkArray(Object.values(userRecord))){
      errorMsg.value="员工 (A固定评三个,D和E最少三个)"
      errorShow.value=true
      return
    }
    //员工部门至少一个D一个E
    RecordAdd({deptRecord: JSON.stringify(deptRecord),userRecord:JSON.stringify(userRecord),deptSituationRecord:JSON.stringify(deptSituationRecord),userSituationRecord:JSON.stringify(userSituationRecord)}).then(res => {
      router.push({
        path: "/questionnaire"
      })
    })
  })
}

function checkArray(arr) {
    // 参数验证
   
    if (!Array.isArray(arr)) {
        return false;
    }
    
    // 统计各数字出现次数
    let zeroCount = 0;
    let threeFourCount = 0;
    
    for (const num of arr) {
        if (num == 'A') zeroCount++;
        if (num == 'D' || num == 'E') threeFourCount++;
    }
    // 检查条件
    return zeroCount === 3 && threeFourCount >= 3;
}
</script>

<style scoped>
.questionnaire {
  width: 100%;
}

.van-cell-group {
  margin: 0;
}

.zdyField {
  flex-direction: column;
}

::v-deep(.zdyField .van-cell__title, .van-cell .van-cell__title) {
  width: 100% !important;
  color: #315FFF;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;

}

::v-deep(.cField .van-cell__title) {
  background: transparent;
  color: #315FFF;
  font-size: .4267rem;


}

.cField,
.zdyField,
.van-cell {
  background: transparent !important;
}

::v-deep(.van-radio-group) {
  display: flex;
  gap: 20px;
}

.contentBg {
  background-image: url("../assets/hbg.png");
  background-size: 100% 100%;
  padding: 20px;
}

.contentBg-title {
  font-size: 24px;
  text-align: left;
  font-weight: bold;
}

.contentBg-title span {
  font-size: 14px;
  color: red;
}

.contentBg-dept {
  font-size: 16px;
  margin: 10px 0;
  background: #325FFF;
  padding: 5px 40px;
  display: inline-block;
  color: #fff;
  font-weight: bold;
  border-radius: 20px;
}

:deep(.van-radio__icon .van-icon) {
  border-color: #8b96c0;
}

:deep(.van-radio__icon--checked .van-icon) {
  border-color: #325FFF;
}

:deep(.van-field__control::-webkit-input-placeholder) {
  color: #8b96c0;

}

.reason {
  font-size: 16px;
}

:deep(.van-field__body textarea) {
  border: 1px solid #8b96c0;
  padding: 5px;
  border-radius: 10px;
}
.errorImg{
  width: 60px;
  height: 60px;
}
</style>
